package com.platform.framework.controller.rights;

import java.security.MessageDigest;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.platform.common.utils.JsonUtils;
import com.platform.common.utils.PageUtils;
import com.platform.common.utils.StringUtils;
import com.platform.framework.controller.BaseController;
import com.platform.framework.entity.rights.FwRightRoleUserRef;
import com.platform.framework.entity.rights.FwRightUser;
import com.platform.framework.service.rights.FwRightUserService;

@RestController
@RequestMapping("/user")
public class FwRightUserController extends BaseController {


	
	@Autowired
	FwRightUserService fwRightUserService;

	/**
	 * 
	 * user分页数据
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "userList", method = { RequestMethod.POST })
	public String roleList(HttpServletRequest request) throws Exception {
		
		String searchCtx = request.getParameter("searchPhrase");//查询条件框
		String orgId = request.getParameter("orgId");
		//current=1&rowCount=10&sort[sender]=asc&searchPhrase=&id=b0df282a-0d67-40e5-8558-c9e93b7befed
		//current=1&rowCount=10&sort[sender]=asc&searchPhrase=
		
		//System.out.println(usercode+"----------");
		//Sort sort = new Sort(Sort.Direction.DESC, "id");
		//Pageable pageable = new PageRequest(0, 10, sort); //查询十条数据
		Pageable pageable = null;
		try{
			pageable = PageUtils.dealminiRequest(request);
		}catch (Exception e) {
			e.printStackTrace();
		}
		Page<FwRightUser> pages= null;
		if(StringUtils.isNull(orgId)||orgId.equals("1")){
			 pages= fwRightUserService.findUserPage(searchCtx,pageable);//查询所有用户
		}else{
			 pages= fwRightUserService.findParentPage(orgId,pageable);//查询所属组织机构的用户
		}
		return JsonUtils.dealMiniPage(pages);
	}
	
	
	  
    @PreAuthorize("hasAuthority('user')")//有用户添加权限的才能访问  
    @RequestMapping("/index")  
    public ModelAndView userIndex() {
    	ModelAndView mv = new ModelAndView("rights/user/index");
		return mv;
    }  
    @PreAuthorize("hasAuthority('user')")//有用户添加权限的才能访问  
    @RequestMapping("/roleIndex")  
    public ModelAndView roleIndex() {
    	ModelAndView mv = new ModelAndView("rights/user/roleIndex");
    	return mv;
    }  
	
    /**
	 * 
	  * 用户管理添加，修改页面界面 	
	  * @author 王求卿[wangqiuqing] Email:455654995@qq.com Tel:18101037995
	  * @return
	  * @createDate 2017-7-13 上午9:37:43
	  * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
    @RequestMapping("/edit")  
    public ModelAndView orgAdd(){
    	ModelAndView mv = new ModelAndView("rights/user/edit");
		return mv;
    }
    /**
	 * 
	  * 添加用户 	
	  * @author李增冰[lizengbing] Email:767656653@qq.com Tel:13807031023
	  * @return 
	  * @createDate 2017-7-19 下午13:34:55
	  * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]	 */
	@PreAuthorize("hasAuthority('user:add')")
	@RequestMapping(value = "add", method = { RequestMethod.POST })
	public String userSave(HttpServletRequest request){
		String data = request.getParameter("data");
		FwRightUser fwRightUser =  JSONObject.parseObject(data, FwRightUser.class);
		fwRightUser.setId(this.getUUID());
		fwRightUser.setCreateTime(new Date());
		fwRightUser.setCreateUserCode(this.getUserId());//操作用户
		fwRightUser.setCreateUserName(this.getUserCode());//操作编码
		fwRightUser.setIsDeleted("0");//未删除
		fwRightUser.setIsEnable("1");//可用
		fwRightUser.setRegTime(new Date());//注册时间
		/**
		 * 如果密码没有设置，则为空
		 */
		if(null == fwRightUser.getPassword() || StringUtils.isNull(fwRightUser.getPassword())){
			fwRightUser.setPassword(this.MD5("111111"));
		}else{
			fwRightUser.setPassword(this.MD5(fwRightUser.getPassword()));
		}
		
		return fwRightUserService.saveUser(fwRightUser);
	}
	/**
	 * 
	 * 更新用户信息 	
	 * @author李增冰[lizengbing] Email:767656653@qq.com Tel:13807031023
	 * @return 
	 * @createDate 2017-7-19 下午13:34:55
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]	 */
	@PreAuthorize("hasAuthority('user:update')")
	@RequestMapping(value = "update", method = { RequestMethod.POST })
	public String userUpdate(HttpServletRequest request){
		String data = request.getParameter("data");
		FwRightUser fwRightUser =  JSONObject.parseObject(data, FwRightUser.class);
		fwRightUser.setUpdateTime(new Date());
		fwRightUser.setUpdateUserCode(this.getUserId());
		fwRightUser.setUpdateUserName(this.getUserCode());
		fwRightUser.setIsDeleted("0");
		if(null != fwRightUser.getPassword() && !StringUtils.isNull(fwRightUser.getPassword())){
			fwRightUser.setPassword(this.MD5(fwRightUser.getPassword()));
		}
		return fwRightUserService.updateUser(fwRightUser);
	}
	
	/**
	 * 判断userCode是否可用,1表示可用，0表示不可用
	 * @param userCode
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "isExist/{userCode}", method = RequestMethod.GET)
	public String isExistUser(@PathVariable String userCode) throws Exception{
		
		return fwRightUserService.isExistUser(userCode);
	}
	/**
	 * 
	 * 角色分配
	 * @author李增冰[lizengbing] Email:767656653@qq.com Tel:13807031023
	 * @return 
	 * @createDate 2017-7-19 下午13:34:55
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]	 */
	@PreAuthorize("hasAuthority('user:toRole')")
	@RequestMapping(value = "toRole", method = { RequestMethod.POST })
	public String userToRole(HttpServletRequest request){
		String userId = request.getParameter("userId");
		String roleId = request.getParameter("roleId");
		return fwRightUserService.userToRole(userId, roleId);
	}
	/**
	 * 
	 * 查询用户角色信息
	 * @author李增冰[lizengbing] Email:767656653@qq.com Tel:13807031023
	 * @return 
	 * @throws Exception 
	 * @createDate 2017-7-19 下午13:34:55
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]	 */
	@RequestMapping(value = "userRoleIndex", method = { RequestMethod.POST })
	public String userRoleIndex(HttpServletRequest request) throws Exception{
		String userId = request.getParameter("userId");
		List<FwRightRoleUserRef> lists =  fwRightUserService.findUserRoles(userId);
		return JsonUtils.dealJson(lists);
	}
	/**
	 * 
	 * 删除用户 	
	 * @author李增冰[lizengbing] Email:767656653@qq.com Tel:13807031023
	 * @return 
	 * @createDate 2017-7-19 下午13:34:55
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]	 */
	@PreAuthorize("hasAuthority('user:delete')")
	@RequestMapping(value = "delete", method = { RequestMethod.DELETE })
	public String userDelete_get(HttpServletRequest request){
		String ids = request.getParameter("ids");
		return fwRightUserService.deleteUser(ids);
	}
	/**
	 * 
	  * <p>功能描述：MD5加密。</p>	
	  * @param 原密码。
	  * @return MD5加密后密码。
	  * @since JDK1.6。
	  * <p>创建日期:2014-4-28 上午10:33:01。</p>
	  * <p>更新日期:[日期YYYY-MM-DD][更改人姓名][变更描述]。</p>
	 */
	public String MD5(String s) {
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};       

        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
	
	@PreAuthorize("hasAuthority('user:add')")
	@RequestMapping(value = "addSM3", method = { RequestMethod.POST })
	public String userSaveSM3(HttpServletRequest request){
		String data = request.getParameter("data");
		FwRightUser fwRightUser =  JSONObject.parseObject(data, FwRightUser.class);
		fwRightUser.setId(this.getUUID());
		fwRightUser.setCreateTime(new Date());
		fwRightUser.setCreateUserCode(this.getUserId());//操作用户
		fwRightUser.setCreateUserName(this.getUserCode());//操作编码
		fwRightUser.setIsDeleted("0");//未删除
		fwRightUser.setIsEnable("1");//可用
		fwRightUser.setRegTime(new Date());//注册时间
		try {
			//String password = new String(SM4Utils.sm3Encrypt(fwRightUser.getPassword().getBytes()));
			//fwRightUser.setPassword(password);
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		return fwRightUserService.saveUser(fwRightUser);
	}
}